<template>
    <div class="form-container">
        <header>
            <span>
                <el-page-header content="合同申请" @back="onClose" />
            </span>
            <span>
                <el-button v-if="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-if="showReviewBtn" type="primary" @click="onReview">审核</el-button>
                <el-button type="default" @click="onPrint">打印</el-button>
            </span>
        </header>
        <div class="form-content">
            <el-form :model="ruleForm" class="form-info" :rules="rules" ref="ruleFormRef">
                <span class="form-title">合同信息</span>
                <el-form-item label="项目编号" prop="projectCode">
                    <el-input
                        v-model="ruleForm.projectCode"
                        placeholder="请选择项目"
                        readonly
                        @click.native="chooseProject"
                    ></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="projectName">
                    <el-input
                        v-model="ruleForm.projectName"
                        placeholder="请选择项目"
                        readonly
                        @click.native="chooseProject"
                    ></el-input>
                </el-form-item>
                <el-form-item label="合同编号" prop="contractNo">
                    <el-input v-model="ruleForm.contractNo" placeholder="请输入合同编号"></el-input>
                </el-form-item>
                <el-form-item label="合同名称" prop="contractName">
                    <el-input v-model="ruleForm.contractName" placeholder="请输入合同名称"></el-input>
                </el-form-item>
                <el-form-item label="签约方名称" prop="signerName">
                    <el-input v-model="ruleForm.signerName" placeholder="请输入签约方名称"></el-input>
                </el-form-item>
                <el-form-item label="集团领导" prop="groupLeader">
                    <el-input v-model="ruleForm.groupLeader" placeholder="请输入集团领导"></el-input>
                </el-form-item>
                <el-form-item label="承担部门" prop="departmentName">
                    <el-input
                        v-model="ruleForm.departmentName"
                        placeholder="承担部门"
                        readonly
                        @click="chooseDepartment('1')"
                    ></el-input>
                </el-form-item>
                <el-form-item label="主办部门" prop="organizeDepartment">
                    <el-input
                        v-model="ruleForm.organizeDepartment"
                        placeholder="主办部门"
                        readonly
                        @click="chooseDepartment('2')"
                    ></el-input>
                </el-form-item>
                <el-form-item label="办事处" prop="branchOffice">
                    <el-input v-model="ruleForm.branchOffice" placeholder="请输入办事处" @click="chooseOffice"></el-input>
                </el-form-item>
                <el-form-item label="款项类型" prop="paymentsType">
                    <el-select v-model="ruleForm.paymentsType" placeholder="请选择款项类型">
                        <el-option
                            v-for="item in paymentsTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合同类型" prop="contractType">
                    <el-select v-model="ruleForm.contractType" placeholder="请选择合同类型">
                        <el-option
                            v-for="item in contractTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合同净额(元)" prop="contractNetFee">
                    <el-input v-model="ruleForm.contractNetFee" placeholder="请输入合同净额，单位：元"></el-input>
                </el-form-item>
                <span class="form-title">附件信息</span>
                <div style="width: 100%">
                    <div v-show="showSaveBtn" style="padding: 10px">
                        <el-upload
                            :action="uploadUrl"
                            :headers="uploadHeaders"
                            :on-success="onFileUploadSuccess"
                            :show-file-list="false"
                        >
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                    </div>
                    <el-table :data="ruleForm.attachments" border>
                        <el-table-column type="index" width="80" label="序号" />
                        <el-table-column prop="fileName" label="文件名" />
                        <el-table-column prop="createTime" label="上传时间" width="200" />
                        <el-table-column fixed="right" label="操作" width="200">
                            <template #default="scope">
                                <el-button type="primary" @click="handlePreview(scope.row)" size="small">
                                    预览
                                </el-button>
                                <el-button
                                    type="danger"
                                    @click.prevent="handleRemove(scope.$index, ruleForm.attachments)"
                                    size="small"
                                >
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <span class="form-title">审批流程</span>
                <FlowCpt
                    ref="processRef"
                    :flowType="flowTypeCode"
                    :disabled="!showSaveBtn"
                    :taskId="props.taskId"
                ></FlowCpt>
                <FlowOperationCpt
                    v-if="showReviewDialog"
                    :data="ruleForm"
                    @close="closeReviewDialog"
                ></FlowOperationCpt>
                <span class="form-title" v-if="showFlowHis">审批记录</span>
                <FlowHistoryCpt v-if="showFlowHis" :taskId="props.taskId" />
            </el-form>
        </div>
        <!-- 项目弹框 -->
        <el-dialog
            title="项目信息"
            v-model="showProjectGridCpt"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <ProjectGridCpt
                v-if="showProjectGridCpt"
                statuses="'TEMP', 'BID_WIN', 'IN_PA', 'HAS_PA'"
                @select="projectSelected"
            ></ProjectGridCpt>
        </el-dialog>
        <!-- 部门弹框 -->
        <el-dialog
            title="选择部门"
            v-model="showDepartment"
            width="400px"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <div class="tree-dialog-content">
                <department-tree v-if="showDepartment" @select="departmentSelected"></department-tree>
            </div>
        </el-dialog>
        <el-dialog
            width="800px"
            top="10vh"
            title="办事处"
            v-model="showOfficeGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <OfficeGridCpt :single="true" @select="officeSelected"></OfficeGridCpt>
            </div>
        </el-dialog>
        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate :id="props.taskId"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { reactive, ref, unref, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import OfficeGridCpt from '@/components/pub/OfficeGridCpt.vue'
import PrintTemplate from '@/print/yunying/ContractPrint.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    taskId: {
        type: String,
        default: ''
    }
})

onMounted(() => {
    if (props.taskId !== '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
    }
})

const flowTypeCode = 'CONTRACT'

const rules = {
    projectCode: [{ required: true, message: '', trigger: 'change' }],
    projectName: [{ required: true, message: '', trigger: 'change' }],
    contractName: [{ required: true, message: '', trigger: 'blur' }],
    signerName: [{ required: true, message: '', trigger: 'blur' }],
    departmentName: [{ required: true, message: '', trigger: 'change' }],
    organizeDepartment: [{ required: true, message: '', trigger: 'change' }],
    branchOffice: [{ required: true, message: '', trigger: 'blur' }],
    paymentsType: [{ required: true, message: '', trigger: 'change' }],
    contractType: [{ required: true, message: '', trigger: 'change' }],
    contractNetFee: [{ required: true, message: '', trigger: 'blur' }],
    currentHandler: [{ required: true, message: '', trigger: 'blur' }],
    state: [{ required: true, message: '', trigger: 'blur' }]
}
// 表单初始化
let ruleForm = reactive({
    projectCode: '',
    projectName: '',
    contractNo: '',
    contractName: '',
    signerName: '',
    departmentName: '',
    organizeDepartment: '',
    branchOffice: '',
    paymentsType: '',
    contractType: '',
    groupLeader: '',
    contractNetFee: '',
    flowTypeCode: flowTypeCode,
    state: '',
    stateName: '',
    handler: '',
    handlerName: '',
    attachments: []
})

const paymentsTypeOptions = [
    { label: '总价', value: 0 },
    { label: '开口', value: 1 },
    { label: '结算单', value: 2 },
    { label: '投标补偿金', value: 3 },
    { label: '代收代付', value: 4 }
]
const contractTypeOptions = [
    { label: '工程咨询', value: 0 },
    { label: '工程施工', value: 1 },
    { label: '材料销售', value: 2 },
    { label: '其他', value: 3 }
]

const processRef = ref(null)
const showSaveBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)
const showFlowHis = ref(false)

const loadDetail = () => {
    http.fetchForm({
        url: '/yunying/contract/findById',
        data: {
            taskId: props.taskId
        }
    }).then((res) => {
        // 基本信息
        ruleForm = Object.assign(ruleForm, res.data)

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (ruleForm.state == 0 && ruleForm.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (ruleForm.state != 0 && ruleForm.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true

        ruleForm.contractNetFee = ruleForm.contractNetFee / 100
    })
}

// 返回主页面,子组件向父组件传值
const emit = defineEmits(['close'])
const onClose = (params) => {
    emit('close')
}

// 表单提交
const ruleFormRef = ref(null)
const onSubmit = async () => {
    if (validate(ruleForm)) {
        let params = JSON.parse(JSON.stringify(ruleForm))
        params.contractNetFee = parseFloat(params.contractNetFee) * 100
        let processData = processRef.value.processList
        params['flowList'] = processData
        http.fetchJson({
            url: '/yunying/contract/save',
            data: params
        }).then((res) => {
            ElNotification({
                title: '提示',
                message: res.message,
                type: 'success'
            })
            onClose()
        })
    } else {
        ElNotification({
            title: '提示',
            message: '打*项必填',
            type: 'warning'
        })
    }
}

// 判断必填字段
const validate = (ruleForm) => {
    if (ruleForm.projectCode === null || ruleForm.projectCode === '') return false
    if (ruleForm.projectName === null || ruleForm.projectName === '') return false
    if (ruleForm.contractName === null || ruleForm.contractName === '') return false
    if (ruleForm.signerName === null || ruleForm.signerName === '') return false
    if (ruleForm.organizeDepartment === null || ruleForm.organizeDepartment === '') return false
    if (ruleForm.branchOffice === null || ruleForm.branchOffice === '') return false
    if (ruleForm.paymentsType === null || ruleForm.paymentsType === '') return false
    if (ruleForm.contractType === null || ruleForm.contractType === '') return false
    if (ruleForm.contractNetFee === null || ruleForm.contractNetFee === '') return false
    return true
}

// 重置
const reset = () => {
    const form = unref(ruleFormRef)
    form.resetField()
}

// 审核
const onReview = (refresh) => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

// 项目选择
const showProjectGridCpt = ref(false)
const chooseProject = () => {
    showProjectGridCpt.value = true
}

const projectSelected = (params) => {
    ruleForm.projectName = params[0].name
    ruleForm.projectCode = params[0].code
    ruleForm.departmentName = params[0].departmentName
    ruleForm.organizeDepartment = params[0].organizeDepartment
    ruleForm.branchOffice = params[0].branchOffice
    showProjectGridCpt.value = false
}

// 部门选择
const showDepartment = ref(false)
const departmentType = ref('')
const chooseDepartment = (type) => {
    departmentType.value = type
    showDepartment.value = true
}

const departmentSelected = (params) => {
    if (departmentType.value === '1') {
        ruleForm.departmentName = params.label
    } else if (departmentType.value === '2') {
        ruleForm.organizeDepartment = params.label
    }
    showDepartment.value = false
}

/**
 * 办事处选择
 */
const showOfficeGridCpt = ref(false)

const chooseOffice = () => {
    showOfficeGridCpt.value = true
}

const officeSelected = (res) => {
    ruleForm.branchOffice = res.name
    showOfficeGridCpt.value = false
}

// 打印
const showPrint = ref(false)
const onPrint = () => {
    showPrint.value = true
}

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/sys/file/upload')
const uploadHeaders = reactive({
    Authorization: localStorage.getItem('token')
})

const onFileUploadSuccess = (response) => {
    let json = {
        category: 0,
        fileName: response.data.fileName,
        storageName: response.data.storageName,
        storagePath: response.data.storagePath
    }
    ruleForm.attachments.push(json)
}

const handlePreview = (row) => {
    let url = import.meta.env.VITE_API_URL + '/attachment/' + row.storageName
    window.open(url)
}

const handleRemove = (index, rows) => {
    rows.splice(index, 1)
}
</script>
<style scoped>
@import '@/assets/css/form.css';
</style>
